package com.bosssoft.trainee.common.handler;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * @Author: wuxin
 * @Project: rbac
 * @Date: 2022/6/23
 * @Description:
 */
@Slf4j
@Component
public class ObjectToStringHandler implements TypeHandler<Object> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws SQLException {
        log.info("将Object转为Json字符串存入数据库...");
        preparedStatement.setString(i, JSONUtil.parse(o).toString());
    }

    @Override
    public Object getResult(ResultSet resultSet, String s) throws SQLException {
        String jsonStr = resultSet.getString(s);
        if (JSONUtil.isJson(jsonStr)){
            log.info("ResultSet-String:将读取的Json字符串转为Object...");
            return JSONUtil.parseObj(jsonStr);
        }else{
            log.error("ResultSet-String:非Json字符串");
            return null;
        }
    }

    @Override
    public Object getResult(ResultSet resultSet, int i) throws SQLException {
        String jsonStr = resultSet.getString(i);
        if (JSONUtil.isJson(jsonStr)){
            log.info("ResultSet-Integer:将读取的Json字符串转为Object...");
            return JSONUtil.parseObj(jsonStr);
        }else{
            log.error("ResultSet-Integer:非Json字符串");
            return null;
        }
    }

    @Override
    public Object getResult(CallableStatement callableStatement, int i) throws SQLException {
        String jsonStr = callableStatement.getString(i);
        if (JSONUtil.isJson(jsonStr)){
            log.info("CallableStatement-Integer:将读取的Json字符串转为Object...");
            return JSONUtil.parseObj(jsonStr);
        }else{
            log.error("CallableStatement-Integer:非Json字符串");
            return null;
        }
    }
}